<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item v-if="isAuth('hotel:hotelseller:list')">
        <el-select
          multiple
          collapse-tags
          clearable
          style="width:180px;"
          v-model="sellerIds"
          filterable
          remote
          reserve-keyword
          @change="selectSeller"
          placeholder="商家名称"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option v-for="item in platformSeller" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.name" placeholder="商品名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="商品分类" prop="cateName">
        <el-popover ref="cateListPopover" placement="bottom-start" trigger="click">
          <el-tree
            :data="cateList"
            :props="cateListTreeProps"
            node-key="id"
            ref="cateListTree"
            @current-change="cateListTreeCurrentChangeHandle"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false"
          ></el-tree>
        </el-popover>
        <el-input
          v-model="dataForm.categoryName"
          v-popover:cateListPopover
          placeholder="点击选择商品分类"
          class="menu-list__input"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">{{ $t('Common.Query') }}</el-button>
        <el-button v-if="isAuth('app:goods:save')" type="primary" @click="addOrUpdateHandle()">{{ $t('Common.Insert') }}</el-button>
        <el-button
          v-if="isAuth('app:goods:delete')"
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
        >{{ $t('Common.BulkDelete') }}</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border=""
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="sellerName" header-align="center" align="center" label="商家"></el-table-column>
      <el-table-column prop="name" header-align="center" align="center" label="商品名称"></el-table-column>
      <el-table-column prop="categoryName" header-align="center" align="center" label="分类"></el-table-column>
      <el-table-column prop="img" header-align="center" align="center" label="商品图片">
        <template slot-scope="scope">
          <img-view :imgSrc="scope.row.img" :styleObject="styleObject"></img-view>
        </template>
      </el-table-column>
      <el-table-column prop="sales" header-align="center" align="center" label="销量"></el-table-column>
      <el-table-column prop="isNew" header-align="center" align="center" label="新品">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isNew === 0" size="small">否</el-tag>
          <el-tag v-if="scope.row.isNew === 1" size="small">是</el-tag>
        </template>ƒ
      </el-table-column>
      <el-table-column prop="isNew" header-align="center" align="center" label="热销">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isNew === 0" size="small">否</el-tag>
          <el-tag v-if="scope.row.isNew === 1" size="small">是</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column prop="sort" header-align="center" align="center" label="商品排序"></el-table-column>-->
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="updateNewHot(scope.row,1)">{{scope.row.isNew === 1 ? "普通" : "新品" }}</el-button>
          <el-button type="text" size="small" @click="updateNewHot(scope.row,2)">{{scope.row.isHot === 1 ? "普通" : "热销" }}</el-button>
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id,scope.row.name)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
  import { treeDataTranslate } from "@/utils";
import AddOrUpdate from "./goods-add-or-update";
export default {
  data() {
    return {
      dataForm: {
        name: undefined,
        categoryName:""
      },
      loading:false,
      sellerIds:[],
      platformSeller:[],
      cateList: [],
      cateListTreeProps: {
        label: "name",
        children: "children"
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      styleObject: {
        wdith: '80px',
        height: '80px'
      }
    };
  },
  components: {
    AddOrUpdate
  },
  activated() {
    this.loadCategory();
    this.remoteMethod();
    this.getDataList();
  },
  methods: {
    selectSeller(id,value) {
      this.getDataList();
      //this.getExecuteUserId();
    },
    remoteMethod(query) {
      if (this.isAuth('hotel:hotelseller:list')) {
        this.loading = true;
        this.$http({
          url: this.$http.adornUrl("/hotel/hotelseller/platformSeller"),
          method: "get",
          params: this.$http.adornParams({
            sellerName: query
          })
        }).then(({ data }) => {
          this.loading = false;
          if (data && data.code === 0) {
            this.platformSeller = data.page.list;
          } else {
            this.$message.error(data.msg);
          }
        });
      }
    },
    // 分类树选中
    cateListTreeCurrentChangeHandle(data, node) {
      this.dataForm.categoryId = data.id;
      this.dataForm.categoryName = data.name;
      this.$refs.cateListPopover.doClose();
    },
    // 分类输设置当前选中节点
    cateListTreeSetCurrentNode() {
      this.$refs.cateListTree.setCurrentKey(this.dataForm.categoryId);

      // eslint-disable-next-line
      this.dataForm.categoryName = (this.$refs.cateListTree.getCurrentNode() || {})[
        "name"
        ];
    },
    //加载商品分类
    async loadCategory() {
      this.$http({
        url: this.$http.adornUrl(`/admin/category/list`),
        method: "get",
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.cateList = treeDataTranslate(data.data, "id", "pid");
        }
      });
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      if (!this.dataForm.categoryName && this.dataForm.categoryName === "") {
        this.dataForm.categoryId = undefined;
      }
      var ids = '';
      if (this.sellerIds) {
        ids = this.sellerIds.join(",");
      }
      this.$http({
        url: this.$http.adornUrl("/admin/goods/list"),
        method: "get",
        params: this.$http.adornParams({
          current: this.pageIndex,
          ...this.dataForm,
          size: this.pageSize,
          key: this.dataForm.key,
          sellerIds:ids
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.data.list.map(l=>{
            if (l.img && l.img.split(",").length > 0) {
              l.img = l.img.split(",")[0]
            }
            return l;
          });

          this.totalPage = data.data.total;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.$router.push({
        path: "/app-goods/goods-add-or-update",
        query: {
          id: id
        }
      });

      // this.$router.push({
      //   name: "goods-add-or-update",
      //   params: {
      //     id: id
      //   }
      // });
      // this.addOrUpdateVisible = true;
      // this.$nextTick(() => {
      //   this.$refs.addOrUpdate.init(id);
      // });
    },
    updateNewHot(goods,type) {
      const isNew = goods.isNew > 0 ? 0 : 1;
      const isHot = goods.isHot > 0 ? 0 : 1;
      this.$http({
        url: this.$http.adornUrl("/admin/goods/udpateGoods"),
        method: "post",
        data: this.$http.adornData({ id:goods.id, isNew: type == 1 ? isNew : undefined, isHot: type === 2 ? isHot : undefined })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.getDataList();
            }
          });
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 删除
    deleteHandle(id,name) {
      var ids = [id];
      var names = name
        ? [name]
        : this.dataListSelections.map(item => {
            return item.name;
          });
      if (id == null) {
        ids = this.dataListSelections.map(item => item.id);
      }
      this.$confirm(
        `确定对[商品:${names.join(",")}]进行[${name ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/admin/goods/delete"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    }
  }
};
</script>
